package io.potato.ts.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.TransactionInterceptor;

/**
 *
 *时区问题，  要手工设置数据库的时区
set global time_zone='+08:00';
set time_zone = '+08:00';
show variables like '%time_zone:' 

 * @author timl
 * created: 2018年11月9日 上午9:35:30
 */
@Configuration
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ, proxyTargetClass = true)
@EnableJpaRepositories("io.potato.ts.repository")
@EntityScan("io.potato.ts.domain")
public class DatabaseConfig {
	
	@Autowired
    private DataSource dataSource;
	
	/*@Autowired
    private DataSourceTransactionManager transactionManager;*/
	
	@Bean
    @ConditionalOnMissingBean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
 
    // 创建事务通知
    @Bean(name = "txAdvice")
    public TransactionInterceptor getAdvisor() throws Exception {
 
        Properties properties = new Properties();
        properties.setProperty("get*",   "PROPAGATION_SUPPORTS,-Exception");
        properties.setProperty("find*",  "PROPAGATION_SUPPORTS,-Exception");
        properties.setProperty("query*", "PROPAGATION_SUPPORTS,-Exception");
        
        properties.setProperty("add*",    "PROPAGATION_REQUIRED,-Exception");
        properties.setProperty("save*",   "PROPAGATION_REQUIRED,-Exception");
        properties.setProperty("update*", "PROPAGATION_REQUIRED,-Exception");
        properties.setProperty("delete*", "PROPAGATION_REQUIRED,-Exception");
        properties.setProperty("batch*",  "PROPAGATION_REQUIRED,-Exception");
        properties.setProperty("bulk*",   "PROPAGATION_REQUIRED,-Exception");
 
        return new TransactionInterceptor(transactionManager(), properties);
    }
 
    @Bean
    public BeanNameAutoProxyCreator txProxy() {
        BeanNameAutoProxyCreator creator = new BeanNameAutoProxyCreator();
        creator.setInterceptorNames("txAdvice");
        creator.setBeanNames("*Service");
        creator.setProxyTargetClass(true);
        return creator;
    }
}
